import React, { useState } from 'react';
import { Card, Input, InputNumber, Select, Form } from 'antd';
import { withPropsAPI } from '@/components/GGEditor';
import Connect from '@/components/Connect';
import useModel from '../../useModel';

const upperFirst = str => str.toLowerCase().replace(/( |^)[a-z]/g, l => l.toUpperCase());

const { Item } = Form;
const { Option } = Select;
const inlineFormItemLayout = {
  labelCol: {
    sm: {
      span: 8,
    },
  },
  wrapperCol: {
    sm: {
      span: 16,
    },
  },
};

class DetailForm extends React.Component {
  get item() {
    const { propsAPI } = this.props;
    return propsAPI.getSelected()[0];
  }

  handleFieldChange = values => {
    const { propsAPI } = this.props;
    const { getSelected, executeCommand, update } = propsAPI;
    setTimeout(() => {
      const item = getSelected()[0];

      if (!item) {
        return;
      }

      executeCommand(() => {
        update(item, { ...values });
      });
    }, 0);
  };

  handleInputBlur = type => e => {
    e.preventDefault();
    this.handleFieldChange({
      [type]: e.currentTarget.value,
    });
  };

  renderNodeDetail = () => {};

  renderEdgeDetail = () => {
    const { label = '', shape = 'flow-polyline' } = this.item.getModel();
    return (
      <Form
        initialValues={{
          label,
          shape,
        }}
      >
        <Item label="标签" name="label" {...inlineFormItemLayout}>
          <Input onBlur={this.handleInputBlur('label')} />
        </Item>
        <Item label="形状" name="shape" {...inlineFormItemLayout}>
          <Select
            onChange={value =>
              this.handleFieldChange({
                shape: value,
              })
            }
          >
            <Option value="flow-smooth">平滑线</Option>
            <Option value="flow-polyline">折线</Option>
            <Option value="flow-polyline-round">圆角折线</Option>
          </Select>
        </Item>
      </Form>
    );
  };

  renderGroupDetail = () => {
    const { label = '新建分组' } = this.item.getModel();
    return (
      <Form
        initialValues={{
          label,
        }}
      >
        <Item label="分组名称" name="label" {...inlineFormItemLayout}>
          <Input onBlur={this.handleInputBlur('label')} />
        </Item>
      </Form>
    );
  };

  render() {
    const { type } = this.props;

    if (!this.item) {
      return null;
    }

    return (
      <Card type="inner" size="small" title={upperFirst(type)} bordered={false}>
        {type === 'node' && (
          <RenderNodeDetail
            {...this.props}
            handleFieldChange={this.handleFieldChange}
            handleInputBlur={this.handleInputBlur}
            item={this.item}
          />
        )}
        {type === 'edge' && this.renderEdgeDetail()}
        {type === 'group' && this.renderGroupDetail()}
      </Card>
    );
  }
}
const RenderNodeDetail = props => {
  const {
    state: { fnList, customAllList, ftpFileType = [] },
  } = useModel(model => [model.state.fnList, model.state.ftpFileType, model.state.customAllList]);
  const { item, handleInputBlur, handleFieldChange } = props;

  const { label, data = {}, method = '', schema } = item.getModel();
  const [fields, setFields] = useState(data);
  const formRef = React.createRef();
  const keys = Object.keys(fields);

  const handleFnSelect = type => value => {
    const current = fnList.filter(item => {
      return item.method === value;
    });
    let data = current[0]?.data || {};
    //默认选中第一个
    const hasMsgId = data.hasOwnProperty('msgId');
    if (hasMsgId && customAllList[0]?.id) {
      data['msgId'] = customAllList[0]?.id;
    }
    //form表单赋值
    formRef.current.setFieldsValue({
      ...data,
    });

    //更新显示字段
    setFields(data);

    //更新节点数据
    handleFieldChange({
      [type]: value,
      data: data,
    });
  };
  const handleSelect = type => value => {
    if (typeof value === 'object') {
      value = value?.currentTarget?.value || '';
    }
    handleFieldChange({
      data: {
        ...fields,
        [type]: value,
      },
    });
  };

  return (
    <Form
      ref={formRef}
      initialValues={{
        label,
        method,
        ...fields,
      }}
    >
      <Item label="名称" name="label" {...inlineFormItemLayout}>
        <Input onBlur={handleInputBlur('label')} />
      </Item>
      {schema !== 2 && (
        <Item label="方法体" name="method" {...inlineFormItemLayout}>
          <Select onChange={handleFnSelect('method')}>
            {fnList
              .filter(item => {
                return item.schema.includes(schema);
              })
              .map((item, index) => {
                return (
                  <Option key={index.toString(36) + index} value={item.method}>
                    {item.name}
                  </Option>
                );
              })}
          </Select>
        </Item>
      )}
      {keys.includes('msgId') && (
        <Item label="选择报文" name="msgId" {...inlineFormItemLayout}>
          <Select onChange={handleSelect('msgId')}>
            {customAllList.map((item, index) => {
              return (
                <Option key={index.toString(36) + index} value={item.id}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Item>
      )}
      {keys.includes('ms') && (
        <Item label="等待时间" name="ms" {...inlineFormItemLayout}>
          <InputNumber min={0} onChange={handleSelect('ms')} />
        </Item>
      )}
      {keys.includes('source') && (
        <Item label="上传路径" name="source" {...inlineFormItemLayout}>
          <Select placeholder={'上传文件或目录路径'} onChange={handleSelect('source')}>
            {ftpFileType.map((item, index) => {
              return (
                <Option key={index.toString(36) + index} value={item.code}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Item>
      )}
      {keys.includes('target') && (
        <Item label="ftp路径" name="target" {...inlineFormItemLayout}>
          <Input placeholder={'ftp上的路径'} onBlur={handleSelect('target')} />
        </Item>
      )}
      {keys.includes('from') && (
        <Item label="ftp路径" name="from" {...inlineFormItemLayout}>
          <Input placeholder={'ftp上文件或目录路径'} onBlur={handleSelect('from')} />
        </Item>
      )}
      {keys.includes('to') && (
        <Item label="保存地址" name="to" {...inlineFormItemLayout}>
          <Input placeholder={'保存在本地的地址'} onBlur={handleSelect('to')} />
        </Item>
      )}
    </Form>
  );
};

export default withPropsAPI(DetailForm);
